package com.faith.timefloating.db;


import com.faith.timefloating.model.Quote;

import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;


public class TblQuote {
	public static final String TABLE_NAME = "tbl_quo";

	public class Column {
		public static final String ID = "id";
		public static final String AUTHOR = "aut";
		public static final String QUOTE = "quo";
		public static final String MARK = "mar";
		public static final String TYPE = "typ";
	}
	
	public static void createTable(SQLiteDatabase db) {

		String CREATE_QUOTE_TABLE = "CREATE TABLE " + TABLE_NAME + "(" + Column.ID
				+ " INTEGER PRIMARY KEY AUTOINCREMENT," + Column.AUTHOR
				+ " TEXT," + Column.QUOTE + " TEXT," + Column.MARK + " INTEGER,"
				+ Column.TYPE + " TEXT)";
		db.execSQL(CREATE_QUOTE_TABLE);
	}
//			byte[] mBlob = cursor.getBlob(cursor.getColumnIndex(Column.NAME));
//			if (mBlob != null) {
//				String content = new String(mBlob);
	//update all db
	public static void updateMark(SQLiteDatabase db){
		ContentValues vl = new ContentValues();
		vl.put(Column.MARK, 0);
		int count=db.update(TABLE_NAME, vl, null, null);
//		Log.e("DB update mark","updated "+count+" row");
		db.close();
	}
	
	public static Quote getQuote(SQLiteDatabase db) {
		Quote quo=null;
		int id;
		Cursor c = db.query(TABLE_NAME, new String[] {Column.ID, Column.AUTHOR,Column.QUOTE,Column.TYPE}, Column.MARK+"=0", null, null,null, "RANDOM()", "1");
		if (c.getCount() > 0) {
			c.moveToFirst();
			id=c.getInt(c.getColumnIndex(Column.ID));
			quo = new Quote(c.getString(c.getColumnIndex(Column.AUTHOR)), c.getString(c.getColumnIndex(Column.QUOTE)),1, c.getString(c.getColumnIndex(Column.TYPE)));
			ContentValues vl = new ContentValues();
			vl.put(Column.MARK, 1);
			int count=db.update(TABLE_NAME, vl, Column.ID +"="+id, null);
//			Log.e("DB","updated "+count+" row");
		}else{
			Log.e("DB","out of quote!");
			c = db.query(TABLE_NAME, new String[] {Column.ID, Column.AUTHOR,Column.QUOTE,Column.TYPE},null, null, null,null, "RANDOM()", "1");
			if (c.getCount() > 0) {
				c.moveToFirst();
				id=c.getInt(c.getColumnIndex(Column.ID));
				quo = new Quote(c.getString(c.getColumnIndex(Column.AUTHOR)), c.getString(c.getColumnIndex(Column.QUOTE)), 1, c.getString(c.getColumnIndex(Column.TYPE)));
				ContentValues vl = new ContentValues();
				vl.put(Column.MARK, 1);
				int count=db.update(TABLE_NAME, vl, Column.ID +"="+id, null);
//				Log.e("DB","updated "+count+" row");
			}
		}
		c.close();
		db.close();
		return quo;
	}
	
}
